from flask import Blueprint, request
from marshmallow import ValidationError

from config.database import db
from models.company import Company, company_schema
from utils.res_result import make_response
from utils.role_required import role_required

company_blueprint = Blueprint('company', __name__)


@company_blueprint.route('/companies')
@role_required("ADMIN")
def index():
    page_num = request.args.get('page', 1, type=int)  # 获取页码，默认为第一页
    page_size = request.args.get('pageSize', 20, type=int)  # 获取每页显示的记录数，默认为20
    name = request.args.get('name', '', type=str)
    pagination = Company.query.filter(Company.name.like(f'%{name}%')) \
        .order_by(Company.name).paginate(page=page_num,
                                         per_page=page_size,
                                         error_out=False)
    companies = pagination.items

    return make_response(data={
        "items": [company.to_dict() for company in companies],
        "total": pagination.total
    })


@company_blueprint.route('/', methods=['POST'])
@role_required("ADMIN")
def add_company():
    try:
        data = request.get_json()
        print(data)
        company = company_schema.load(data)
        # company.created_at = datetime.utcnow()
        # company.updated_at = datetime.utcnow()
        db.session.add(company)
        db.session.commit()
        return make_response()
    except ValidationError as err:
        return make_response(code=1, message="field validate failed", status=400)
    finally:
        db.session.close()


@company_blueprint.route('/<string:company_id>', methods=['PUT'])
@role_required("ADMIN")
def edit_company(company_id):
    try:
        data = request.get_json()
        company = Company.query.get_or_404(company_id)
        print(company)
        company_schema.load(data, instance=company, partial=True)
        db.session.commit()
        return make_response()
    except ValidationError as err:
        return make_response(code=1, message="field validate failed", status=400)
    finally:
        db.session.close()


@company_blueprint.route('/<string:company_id>', methods=['DELETE'])
@role_required("ADMIN")
def delete_company(company_id):
    company = Company.query.get_or_404(company_id)
    db.session.delete(company)
    db.session.commit()
    return make_response()
